from django.contrib import admin
from .models import Category, Tag, Article, Comment

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """分类管理"""
    list_display = ['name', 'slug', 'created_at']
    list_filter = ['created_at']
    search_fields = ['name', 'description']
    prepopulated_fields = {'slug': ('name',)}
    ordering = ['name']

@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    """标签管理"""
    list_display = ['name', 'slug', 'created_at']
    list_filter = ['created_at']
    search_fields = ['name']
    prepopulated_fields = {'slug': ('name',)}
    ordering = ['name']

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    """文章管理"""
    list_display = ['title', 'author', 'category', 'status', 'is_featured', 'views', 'created_at']
    list_filter = ['status', 'is_featured', 'category', 'tags', 'created_at', 'updated_at']
    search_fields = ['title', 'content', 'excerpt']
    prepopulated_fields = {'slug': ('title',)}
    filter_horizontal = ['tags']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'slug', 'author', 'category')
        }),
        ('内容', {
            'fields': ('excerpt', 'content', 'featured_image')
        }),
        ('设置', {
            'fields': ('tags', 'status', 'is_featured')
        })
    )
    
    def save_model(self, request, obj, form, change):
        """保存时自动设置作者"""
        if not change:
            obj.author = request.user
        super().save_model(request, obj, form, change)

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    """评论管理"""
    list_display = ['article', 'name', 'email', 'is_approved', 'created_at']
    list_filter = ['is_approved', 'created_at']
    search_fields = ['content', 'name', 'email', 'article__title']
    actions = ['approve_comments', 'disapprove_comments']
    ordering = ['-created_at']
    
    def approve_comments(self, request, queryset):
        """批量审核通过评论"""
        queryset.update(is_approved=True)
        self.message_user(request, f'已审核通过 {queryset.count()} 条评论')
    approve_comments.short_description = '审核通过选中的评论'
    
    def disapprove_comments(self, request, queryset):
        """批量拒绝评论"""
        queryset.update(is_approved=False)
        self.message_user(request, f'已拒绝 {queryset.count()} 条评论')
    disapprove_comments.short_description = '拒绝选中的评论'
